import { defineStore } from "pinia";

interface UserInfo {
  id: string;
  name: string;
  roles: string[];
}

export const useAuthStore = defineStore("authStore", () => {
  const userToken = ref(localStorage.getItem("token") || null);
  const userInfo = ref<UserInfo | null>();

  const isAuthenticated = computed(() => {
    return !!userToken.value;
  });

  const userRoles = computed(() => {
    return userInfo?.value?.roles || [];
  });

  const setToken = (tk: string) => {
    userToken.value = tk;
    localStorage.setItem("token", tk);
  };

  const clearToken = () => {
    userToken.value = null;
    localStorage.removeItem("token");
    userInfo.value = null;
  };

  const setUserInfo = (user: UserInfo) => {
    userInfo.value = user;
  };

  // 检查用户是否拥有指定角色
  const hasRoles = (requiredRoles: string[]): boolean => {
    if (!userInfo.value) return false;
    return requiredRoles.every(role => userRoles.value.includes(role));
  };

  return {
    userToken,
    userInfo,
    isAuthenticated,
    userRoles,
    setToken,
    clearToken,
    setUserInfo,
    hasRoles,
  };
});
